package com.SFA.Login;

import com.FrameWork.Common.AbstractBaseActivity;
import com.FrameWork.Common.CommonFunction;
import com.FrameWork.Common.MainActivity;
import com.FrameWork.Common.MyApplication;
import com.FrameWork.Common.Updater;
import com.FrameWork.DB.DataProvider;
import com.FrameWork.Entity.GlobalInfo;
import com.FrameWork.Synchoronization.SyncActivity;
import com.FrameWork.Synchoronization.SyncModel;
import com.FrameWork.Synchoronization.SyncMonitor;
import com.FrameWork.Synchoronization.SyncProcess;
import com.FrameWork.Synchoronization.SyncProcess_Audit;
import com.FrameWork.Synchoronization.SynchConfig;
import com.FrameWork.Utils.DateTimeUtils;
import com.SFA.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;

/**
 * @author Asion Tang
 */
public class LoginActivity extends AbstractBaseActivity {
	private static final int SHOW_SUBACTIVITY = 1;

	private EditText editText, editText2;
	private Button but_login;
	private CheckBox box, box2;
	private ProgressDialog loginProgress;
	private SharedPreferences preferencce = null;
	private boolean isSavePassword = false; // 是否保存密码
	private boolean isAutomatic = false; // 是否自动登录
	private LoginManager manager;
	private String username;
	private String password;

	/**
	 * 初始化后台数据库
	 */
	private void initDB()
	{
		app.DataProvider = DataProvider.Instance(this);
		app.DataProvider.openDataBase();
		com.umeng.common.Log.LOG = true;
		MobclickAgent.onError(this);


	}

	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		initDB();
		editText = (EditText) findViewById(R.id.login_name);
		editText2 = (EditText) findViewById(R.id.login_password);
		but_login = (Button) findViewById(R.id.login_button);
		box = (CheckBox) findViewById(R.id.b1);
		box2 = (CheckBox) findViewById(R.id.b2);
		manager = new LoginManager((AbstractBaseActivity) context);
		preferencce = this.getSharedPreferences("login", Context.MODE_PRIVATE);
		// 默认执行
		LoginInit();

		editText.setText(username);
		editText2.setText(password);
		box.setChecked(isSavePassword);
		box.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (box2.isChecked()) {
					box2.setChecked(false);
					isSavePassword = false;
				}
			}
		});
		box2.setChecked(isAutomatic);
		box2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (box2.isChecked()) {
					isSavePassword = true;
					box.setChecked(true);
				}
			}
		});
		but_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				username = editText.getText().toString();
				password = editText2.getText().toString();
				if (username.equals("") || password.trim().equals("")) {
					Toast.makeText(LoginActivity.this, "用户名或密码不能为空", 1000)
							.show();
					return;
				}
				isSavePassword = box.isChecked();
				isAutomatic = box2.isChecked();
				Login(isSavePassword, isAutomatic);

			}
		});

	}

	/***
	 * 登录执行
	 */
	public void Login(boolean isSavePassword,
			boolean isAutomatic) {

		/***
		 * 默认保存用户名
		 */
		Editor editor = preferencce.edit();
		editor.putString("LastUser", username);
		/***
		 * 保存密码
		 */
		if (isSavePassword) {
			editor.putString("LastPassword", password);
		} else {
			editor.putString("LastPassword", "");
		}
		// 复选框选中状态
		editor.putBoolean("isSavePassword", isSavePassword);

		/***
		 * 自动登录.（首先也要保存当前密码,然后在保存一个isAutomatic为true）
		 */
		editor.putBoolean("isAutomatic", isAutomatic);
		editor.commit();
		LoginAsynTask asynTask = new LoginAsynTask();
		asynTask.context = this;
		asynTask.execute(username, password);

	}

	private void ShowMain() {
		

		Intent intent = new Intent(this, MainActivity.class);
		intent.setAction(Intent.ACTION_DEFAULT);
		startActivity(intent);
		finish();
		overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
	}

	/**
	 * 
	 * @param type
	 *            0:初始化登录,1:每天第一次登录,2:正常登录
	 */
	private void ShowSynchronization(int loginState) {
		Intent intent = new Intent(this, SyncActivity.class);
		intent.putExtra("loginState", loginState);
		intent.setAction(Intent.ACTION_SYNC);
		this.startActivityForResult(intent, SHOW_SUBACTIVITY);
		overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

		switch (requestCode) {
		case SHOW_SUBACTIVITY: {
			if (resultCode == Activity.RESULT_CANCELED) {
				MyApplication.getInstance().exit();
				// finish();
			} else if (resultCode == SyncActivity.RESULT_SYNCSUCCESSFUL) {

				ShowMain();
			}
			break;
		}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/***
	 * 登录默认执行
	 */
	public void LoginInit() {

		username = preferencce.getString("LastUser", "");
		password = preferencce.getString("LastPassword", "");
		isSavePassword = preferencce.getBoolean("isSavePassword", false);

		isAutomatic = preferencce.getBoolean("isAutomatic", false);
		if (isAutomatic) {
			Login(isSavePassword, isAutomatic);

		} 

	}

	public class LoginAsynTask extends AsyncTask<String, Void, Object> {
		public Context context = null;

		protected Object doInBackground(String... params) {
			
			
			int successful = -2;
			try {
				successful = manager.login(params[0], params[1]);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
			// return true;
			return successful;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			loginProgress = CommonFunction.ShowProgressDialog(context, "正在登陆");
			loginProgress.show();
			
		}

		protected void onPostExecute(Object result) {
			if(loginProgress != null && loginProgress.isShowing())
			{
				loginProgress.dismiss();
				loginProgress = null;
			}
			int code = Integer.parseInt(result.toString()); 
			try {
				if (code == 100) {
					if (GlobalInfo.GetInstance(context).getCabFile() != null) {
						new Updater(LoginActivity.this,GlobalInfo.GetInstance(context).getCabFile()).check();
						return;
					}
					// 设置SynchConfig中的最新密码
					SynchConfig config = SynchConfig
							.Instance(LoginActivity.this);
					
					
					long CurrentTime = Long.parseLong(DateTimeUtils.GetCurrentTime()) / 1000000;
					long LastSyncTime = config.LastSyncTime;
					if (LastSyncTime > 0)
						LastSyncTime = LastSyncTime / 1000000;
					// 如果登陆成功,判断当前的数据同步状态。如果是初始化同步则默认打开同步界面。
					app.SyncMonitor = new SyncMonitor(context);
					app.SyncMonitor.Process = new SyncProcess();
					
					if (config.getSyncModel().equals(SyncModel.InitialSync)) {
						ShowSynchronization(0);
					} else if (CurrentTime > LastSyncTime) {
						ShowSynchronization(1);
					} else {
						ShowMain();
					}

				} else {
	
					String Message = null;
					if (code == -1) {
						Message = getResources().getString(
								R.string.info_NoNetAvailable);
					} else if (code == -2) {
						Message = getResources().getString(
								R.string.info_ConnectServerFail);
					}
					if (code == -3) {
						Message = manager.ErrorMessage;
					}
					CommonFunction.ShowDialog(context, Message);

				}
			} catch (Exception err) {
				MobclickAgent.reportError(LoginActivity.this, err.getMessage());
			}
			super.onPostExecute(result);
		}

		protected void onProgressUpdate(Void... values) {
			super.onProgressUpdate(values);
		}

	}

}
